// pages/manage/manage.js
const app = getApp();
const province = require('../../utils/province.js')
const utils = require("../../utils/util.js");
const ble = require("../../utils/ble.js");
const CRC = require("../../utils/crc8.js");

Page({
  data: {
    provinceSelector: false,
    plateName: '浙',
    plateIdx: 0,
    provinceList: province,
    provinceSelectorShow: false,
    connected: false, // 连接状态
    lineHeight: 0,
    isBinding: false,
    useStatus: 2
  },

  onLoad: function (options) {
    this.initData()
  },

  initData() {
    let idx = app.globalData.plateIdx
    let plateList = app.globalData.plateList
    let connected = app.globalData.connected
    let lineHeight = (wx.getSystemInfoSync().windowWidth - 80) / 8 - 2
    let useStatus = app.globalData.useStatus
    this.setData({
      plateIdx: idx,
      plateList: plateList,
      connected: connected,
      lineHeight: lineHeight,
      useStatus: useStatus
    })
  },

  // 选择车牌card
  checkboxChange(e) {
    let checked = e.detail.value;
    if (checked) {
      let items = [];
      let itm = this.data.plateList
      for (let i = 0; i < itm.length; i++) {
        if (checked.indexOf(itm[i].id.toString()) !== -1) {
          items[i] = Object.assign({}, itm[i], {
            checked: true
          });
        } else {
          items[i] = Object.assign({}, itm[i], {
            checked: false
          });
        }
      }
      this.setData({
        plateList: items
      })
    }
  },

  // 选择城市简称
  chooseProvince(e) {
    let ds = e.currentTarget.dataset
    this.setData({
      plateName: ds.name,
      ['plateList[' + parseInt(this.data.plateIdx) + '].alias']: ds.name,
      ['plateList[' + parseInt(this.data.plateIdx) + '].eName']: ds.ename,
      provinceSelectorShow: false
    })

  },

  // 选择省份
  selectProvince(e) {
    let ds = e.currentTarget.dataset
    this.setData({
      plateName: ds.alias,
      plateIdx: ds.idx,
      provinceSelectorShow: true
    })
  },

  onFocus: function (e) {
    var that = this;
    that.setData({
      ['plateList[' + this.data.plateIdx + '].isFocus']: true
    });
  },

  setValue: function (e) {
    this.setPlateValue(e.detail.value, this.data.plateList[this.data.plateIdx].energy)
  },

  // 输入车牌
  setPlateValue(val, energyVal) {
    let len = val.length
    let max = energyVal ? 7 : 6
    this.setData({
      ['plateList[' + this.data.plateIdx + '].plate']: len > max ? val.substring(0, max).toUpperCase() : val.toUpperCase()
    });
  },

  // 输入密码
  inputPassword(e) {
    let len = e.detail.value.length
    this.setData({
      ['plateList[' + this.data.plateIdx + '].password']: len > 8 ? e.detail.value.substring(0, 8) : e.detail.value
    })
  },

  bindblurPlate(e) {
    let carNum = this.data.plateList[this.data.plateIdx].alias + e.detail.value
    if (this.isVehicleNumber(carNum)) {
      this.setData({
        ['plateList[' + this.data.plateIdx + '].plate']: e.detail.value,
      })
      app.setGlobalData({
        plateList: this.data.plateList,
        estimatePlateNum: carNum
      })
    }
    // else {
    //   wx.showModal({
    //     title: "提示",
    //     content: '车牌格式不正确',
    //     showCancel: false,
    //     success: function (res) {}
    //   });
    // }
  },

  bindblurPassword(e) {
    if ((/^\d{8}?$/.test(e.detail.value))) {
      this.setData({
        ['plateList[' + this.data.plateIdx + '].password']: e.detail.value,
      })
      app.setGlobalData({
        plateList: this.data.plateList,
      })
    } else {
      this.setData({
        ['plateList[' + this.data.plateIdx + '].password']: app.globalData.plateList[this.data.plateIdx].password,
      })
      wx.showModal({
        title: "提示",
        content: '密码必须是8位数字',
        showCancel: false,
        success: function (res) {}
      });
    }
  },

  // 关闭选择省份
  onClose() {
    this.setData({
      provinceSelectorShow: false
    });
  },

  // 切换车牌
  choosePlate(e) {
    let ds = e.currentTarget.dataset
    let plateList = this.data.plateList.map((item, idx) => {
      let _item = item
      _item.checked = false
      if (idx == ds.idx) {
        _item.checked = true
      }
      return _item
    })
    this.setData({
      plateList: plateList,
      plateIdx: ds.idx
    })
    app.setGlobalData({
      plateList: plateList,
      plateIdx: ds.idx,
      connected: false,
      useStatus: 2,
      name: null,
      lockId: null,
      temperature: 0
    })
    // ble.closeBluetoothAdapter();
    // app.globalData.changePalte = true
    wx.navigateBack({
      delta: 1
    })
  },

  // 初始化
  bindInit(e) {
    let that = this
    wx.showModal({
      title: "提示",
      content: '确定要初始化吗?',
      success: function (res) {
        if (res.confirm) {
          that.setData({
            ['plateList[' + that.data.plateIdx + '].alias']: '浙',
            ['plateList[' + that.data.plateIdx + '].eName']: 'ZheJiang',
            ['plateList[' + that.data.plateIdx + '].plate']: 'B0000B',
            ['plateList[' + that.data.plateIdx + '].password']: '12345678',
            ['plateList[' + that.data.plateIdx + '].lockId']: null,
            ['plateList[' + that.data.plateIdx + '].devId']: null,
            ['plateList[' + that.data.plateIdx + '].energy']: false,
            ['plateList[' + that.data.plateIdx + '].isFocus']: false,
            provinceSelectorShow: false
          })
          // console.log(that.data.plateList)
          app.setGlobalData({
            connected: false,
            deviceId: null,
            name: null,
            serviceId: null,
            lockId: null,
            temperature: '0',
            useStatus: 2,
            binding: false,
            changePalte: false,
            isBinding: false,
            plateList: that.data.plateList
          })
        }
      }
    })
  },

  isVehicleNumber(vehicleNumber) {
    var xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
    var creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
    let energy = this.data.plateList[this.data.plateIdx].energy
    if (energy) {
      return xreg.test(vehicleNumber);
    } else {
      return creg.test(vehicleNumber);
    }
    // if (vehicleNumber.length == 7) {
    //   return creg.test(vehicleNumber);
    // } else if (vehicleNumber.length == 8) {
    //   return xreg.test(vehicleNumber);
    // } else {
    //   return false;
    // }
  },

  // 绑定车牌  密码验证指令
  verifyPassword() {
    let carNum = this.data.plateList[this.data.plateIdx].alias + this.data.plateList[this.data.plateIdx].plate
    console.log(carNum)
    if (this.isVehicleNumber(carNum)) {
      app.setGlobalData({
        plateList: this.data.plateList
      })
    } else {
      wx.showModal({
        title: "提示",
        content: '车牌格式不正确',
        showCancel: false,
        success: function (res) {}
      });
    }
  },

  // 改变车牌
  changeBleName() {
    if (this.data.connected && this.data.useStatus === 1) {
      let carNum = this.data.plateList[this.data.plateIdx].alias + this.data.plateList[this.data.plateIdx].plate
      let careNum = this.data.plateList[this.data.plateIdx].eName + this.data.plateList[this.data.plateIdx].plate
      if (this.isVehicleNumber(carNum)) {
        careNum = utils.str2ascii(careNum)
        let order = utils.HexString2Bytes(`E661${careNum}`)
        ble.writeBLECharacteristicValue(order, app.globalData.ffe2CharacteristicId)
        app.setGlobalData({
          plateList: this.data.plateList
        })
      } else {
        wx.showModal({
          title: "提示",
          content: '车牌格式不正确',
          showCancel: false,
          success: function (res) {}
        });
      }
    }
  },

  // 密码修改指令
  changePassword() {
    if (this.data.connected && this.data.useStatus === 1) {
      let pwd = this.data.plateList[this.data.plateIdx].password
      if (/^\d{8}?$/.test(pwd)) {
        let password = utils.decimal2Hex(pwd)
        let crc8 = CRC(`FA0D0B${password}`)
        let orderStr = `FA0D0B${password}${crc8}16`
        let order = utils.HexString2Bytes(orderStr)
        ble.writeBLECharacteristicValue(order)
        app.setGlobalData({
          plateList: this.data.plateList
        })
      } else {
        wx.showModal({
          title: "提示",
          content: '密码必须是8位数字',
          showCancel: false,
          success: function (res) {}
        });
      }
    }
  },

  // 是否新能源
  onCheckBoxChange(e) {
    let energyVal = e.detail.value.length ? true : false
    this.setData({
      ['plateList[' + this.data.plateIdx + '].energy']: energyVal,
      ['plateList[' + this.data.plateIdx + '].isFocus']: energyVal
    })
    app.setGlobalData({
      plateList: this.data.plateList
    })
    this.setPlateValue(this.data.plateList[this.data.plateIdx].plate, energyVal)
  }
})